package qlsl.androiddesign.view.subview.activityview;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.qlsl.androiddesign.kuaiwa.R;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import qlsl.androiddesign.activity.commonactivity.PhotoAddActivity;
import qlsl.androiddesign.activity.subactivity.BrandActivity;
import qlsl.androiddesign.activity.subactivity.CarBuyActivity;
import qlsl.androiddesign.activity.subactivity.MachineActivity;
import qlsl.androiddesign.activity.subactivity.ModelActivity;
import qlsl.androiddesign.activity.subactivity.SellVehicleActivity;
import qlsl.androiddesign.adapter.commonadapter.CarSellAdapter;
import qlsl.androiddesign.entity.otherentity.CarBrand;
import qlsl.androiddesign.http.xutils.HttpProtocol;
import qlsl.androiddesign.library.citypicker.CityPopupWindow;
import qlsl.androiddesign.library.citypicker.CityPopupWindow.OnCitySelectListener;
import qlsl.androiddesign.library.datepicker.TimePopupWindow;
import qlsl.androiddesign.library.datepicker.TimePopupWindow.OnTimeSelectListener;
import qlsl.androiddesign.library.datepicker.TimePopupWindow.Type;
import qlsl.androiddesign.listener.OnUploadFileListener;
import qlsl.androiddesign.method.AppMethod;
import qlsl.androiddesign.method.UserMethod;
import qlsl.androiddesign.util.commonutil.DialogUtil;
import qlsl.androiddesign.util.commonutil.InputMatch;
import qlsl.androiddesign.view.baseview.FunctionView;

/**
 * 卖车页<br/>
 * 需要传入的键：<br/>
 * 传入的值类型： <br/>
 * 传入的值含义：<br/>
 * 是否必传 ：
 */
public class SellVehicle extends FunctionView<SellVehicleActivity> implements
		OnCitySelectListener, OnTimeSelectListener {

	private ListView listView;

	private CityPopupWindow cityWindow;

	private TimePopupWindow timeWindow;

	private CarBrand brand;

	public SellVehicle(SellVehicleActivity activity) {
		super(activity);
		setContentView(R.layout.activity_sell_vehicle_new);
	}

	protected void initView(View view) {
		setTitle("卖车");
		listView = findViewById(R.id.listView);
		cityWindow = new CityPopupWindow(activity, this);
		timeWindow = new TimePopupWindow(activity, Type.YEAR_MONTH_DAY);
	}

	protected void initData() {
		setListViewData();
	}

	protected void initListener() {
		timeWindow.setOnTimeSelectListener(this);
	}

	public <T> void showData(T... t) {

	}

	public <T> void showNoData(T... t) {

	}

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.list_item:
			doClickListItem(view);
			break;
		case R.id.btn_sell:
			doClickSellView();
			break;
		case R.id.tv_check:
			doClickCheckView(view);
			break;
		}
	}

	private void doClickCheckView(View view) {
		view.setActivated(!view.isActivated());
	}

	public void setListViewData() {
		String[] keys = new String[] { "machinevision", "brands", "modelno",
				"type", null, "price", "usedtime", "years", null, "contacter",
				"mobile", "sex" };
		String[] names = new String[] { "机型", "品牌", "型号", "类型", "设备所在地", "价格",
				"使用小时数", "出厂年限", "设备照片", "联系人", "手机号", "身份" };
		String[] values = new String[] { "请选择", "请选择", "请选择", "请选择", "请选择",
				"请输入", "请输入", "请输入", "请选择", "请输入",
				UserMethod.getUser().getMobile(), "请选择" };

		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		for (int index = 0; index < names.length; index++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("text", names[index]);
			map.put("value", values[index]);
			map.put("key", keys[index]);
			list.add(map);
		}
		CarSellAdapter adapter = new CarSellAdapter(activity, list);
		listView.setAdapter(adapter);
	}

	@SuppressWarnings("unchecked")
	private void doClickListItem(View view) {
		int position = listView.getPositionForView(view);
		if (position == 0) {
			startActivityForResult(MachineActivity.class, position);
		} else if (position == 1) {
			startActivityForResult(BrandActivity.class, position);
		} else if (position == 2) {
			if (brand == null) {
				showToast("请选择品牌");
				return;
			}
			Intent intent = new Intent(activity, ModelActivity.class);
			intent.putExtra("brandId", brand.getId());
			startActivityForResult(intent, position);
		} else if (position == 3) {
			startActivityForResult(CarBuyActivity.class, position);
		} else if (position == 4) {
			cityWindow.showAtLocation(view, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
		} else if (position == 5) {
			DialogUtil.showEditTextDialog(this, null, "价格(单位：万元)", "请输入", null,
					position + "");
		} else if (position == 6) {
			DialogUtil.showEditTextDialog(this, null, "使用小时数(单位：小时)", "请输入",
					null, position + "");
		} else if (position == 7) {
			timeWindow.showAtLocation(view, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
		} else if (position == 8) {
			List<File> files = (List<File>) listView.getTag();
			Intent intent = new Intent(activity, PhotoAddActivity.class);
			if (files != null) {
				intent.putExtra("files", (Serializable) files);
			}
			startActivityForResult(intent, position);
		} else if (position == 9) {
			DialogUtil.showEditTextDialog(this, null, "联系人", "请输入", null,
					position + "");
		} else if (position == 10) {
			DialogUtil.showEditTextDialog(this, null, "手机号", "请输入", null,
					position + "");
		} else if (position == 11) {
			HashMap<String, Object> map = (HashMap<String, Object>) listView
					.getAdapter().getItem(11);
			DialogUtil.showSexDialog(map,
					(CarSellAdapter) listView.getAdapter(), this);
		}
	}

	@SuppressWarnings("unchecked")
	private void doClickSellView() {
		List<HashMap<String, Object>> list = ((CarSellAdapter) listView
				.getAdapter()).getList();
		for (HashMap<String, Object> map : list) {
			String value = (String) map.get("value");
			if (value.equals("请输入") || value.equals("请选择")) {
				showToast("请将资料补充完整");
				return;
			}
		}
		setProgressBarText("正在发布");
		showProgressBar();
		HttpProtocol protocol = new HttpProtocol().setMethod("salecar");
		for (int index = 0, size = list.size(); index < size; index++) {
			if (index != 4 && index != 8) {
				HashMap<String, Object> map = list.get(index);
				String key = (String) map.get("key");
				String value = null;
				if (index == 5) {
					value = (String) map.get("price");
				} else if (index == 6) {
					value = (String) map.get("hour");
				} else {
					value = (String) map.get("value");
				}
				protocol.addParam(key, value);
			}
		}
		List<File> files = (List<File>) listView.getTag();
		if (files.size() == 0) {
			showToast("请选择图片");
			return;
		}
		boolean isTop = ((TextView) findViewById(R.id.tv_check)).isActivated();
		HashMap<String, Object> map = (HashMap<String, Object>) listView
				.getAdapter().getItem(4);
		protocol.addParam("province", (String) map.get("province"));
		protocol.addParam("city", (String) map.get("city"));
		protocol.addParam("area", (String) map.get("couny"));
		protocol.removeUserParam()
				.addParam("fuserid", UserMethod.getUser().getUserId())
				.addParam("istop", isTop).uploadFiles(files, null, listener);

	}

	@SuppressWarnings("unchecked")
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0) {
			if (data == null) {
				return;
			}
			String name = data.getStringExtra("name");
			HashMap<String, Object> map = (HashMap<String, Object>) listView
					.getAdapter().getItem(requestCode);
			map.put("value", name);
			((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
		} else if (requestCode == 1) {
			if (data == null) {
				return;
			}
			brand = (CarBrand) data.getSerializableExtra("brand");
			HashMap<String, Object> map = (HashMap<String, Object>) listView
					.getAdapter().getItem(requestCode);
			map.put("value", brand.getName());
			((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
		} else if (requestCode == 2) {
			if (data == null) {
				return;
			}
			String name = data.getStringExtra("name");
			HashMap<String, Object> map = (HashMap<String, Object>) listView
					.getAdapter().getItem(requestCode);
			map.put("value", name);
			((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
		} else if (requestCode == 3) {
			if (data == null) {
				return;
			}
			String name = data.getStringExtra("category");
			HashMap<String, Object> map = (HashMap<String, Object>) listView
					.getAdapter().getItem(requestCode);
			map.put("value", name);
			((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
		} else if (requestCode == 8) {
			if (data == null) {
				return;
			}
			List<File> files = (List<File>) data.getSerializableExtra("files");
			listView.setTag(files);
			String photo_num = "(" + files.size() + "/9)";
			HashMap<String, Object> map = (HashMap<String, Object>) listView
					.getAdapter().getItem(requestCode);
			map.put("value", photo_num);
			((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
		}
	};

	private OnUploadFileListener listener = new OnUploadFileListener() {

		public void onSuccess(JSONObject jo) {
			showToast("发布成功");
			setRefresh(true);
			activity.finish();
		}
	};

	@SuppressWarnings("unchecked")
	public void onClick(DialogInterface dialog, int which) {
		AlertDialog alertDialog = (AlertDialog) dialog;
		if (which == -1) {
			EditText et_content = (EditText) alertDialog
					.findViewById(R.id.et_content);
			String text = et_content.getText().toString();
			if ("5".equals(et_content.getTag())) {
				if (!InputMatch.isPrice(text)) {
					showToast("请输入有效的价格");
					return;
				}
				Double price = Double.parseDouble(text);
				HashMap<String, Object> map = (HashMap<String, Object>) listView
						.getAdapter().getItem(5);
				map.put("value", price + "万元");
				map.put("price", price + "万");
				((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
			} else if ("6".equals(et_content.getTag())) {
				if (!InputMatch.isNumeric(text)) {
					showToast("请输入有效的小时数");
					return;
				}
				Integer hour = Integer.parseInt(text);
				HashMap<String, Object> map = (HashMap<String, Object>) listView
						.getAdapter().getItem(6);
				map.put("value", hour + "小时");
				map.put("hour", hour + "");
				((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
			} else if ("9".equals(et_content.getTag())) {
				if (TextUtils.isEmpty(text)) {
					showToast("未输入");
					return;
				}
				if (text.length() > 4) {
					showToast("名字过长");
					return;
				}
				HashMap<String, Object> map = (HashMap<String, Object>) listView
						.getAdapter().getItem(9);
				map.put("value", text);
				((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
			} else if ("10".equals(et_content.getTag())) {
				if (!InputMatch.isMobileNO(text)) {
					showToast("请输入有效的手机号");
					return;
				}
				HashMap<String, Object> map = (HashMap<String, Object>) listView
						.getAdapter().getItem(10);
				map.put("value", text);
				((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void onTimeSelect(Date date) {
		HashMap<String, Object> map = (HashMap<String, Object>) listView
				.getAdapter().getItem(7);
		map.put("value", AppMethod.formatDate(date, '-').split("-")[0]);
		((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
	}

	@SuppressWarnings("unchecked")
	public void onCitySelect(String city) {
		HashMap<String, Object> map = (HashMap<String, Object>) listView
				.getAdapter().getItem(4);
		map.put("value", city);
		map.put("province", cityWindow.getCityPicker().getProvince());
		map.put("city", cityWindow.getCityPicker().getCity());
		map.put("couny", cityWindow.getCityPicker().getCouny());
		((CarSellAdapter) listView.getAdapter()).notifyDataSetChanged();
	}

}
